package com.foodie.proxy.dynamicproxy;

import com.foodie.proxy.proxycase.RentHouseImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.Test;

import java.lang.reflect.Method;

/**
 * Cglib动态代理
 */
public class CglibDynamicProxy {

    @Test
    public void rentHouseByCglibDynamicProxy() {
        RentHouseImpl rentHoustImpl = new RentHouseImpl();//委托对象

        Object proxy = Enhancer.create(rentHoustImpl.getClass(), new MethodInterceptor() {//参数1：委托对象的类  参数2：MethodInterceptor方法拦截器
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object object = null;
                //功能增强
                System.out.println("收代理租房费300元。");
                //代理本职需要做的事(即调用代理类租房函数)
                object = method.invoke(rentHoustImpl, objects);//参数1：委托对象 参数2：传入函数参数
                //功能增强
                System.out.println("客户信息卖了3毛。");
                return object;
            }
        });
        RentHouseImpl rentHoustCglibProxy = (RentHouseImpl) proxy;
        rentHoustCglibProxy.rentHouse();
    }
}
